<template>
  
  <div
    class="thumbnails"
    @mousedown="() => setThumbnailsFocus(true)"
    v-click-outside="() => setThumbnailsFocus(false)"
    v-contextmenu="contextmenusThumbnails"
  >
    <div class="add-slide">
      <div class="btn">场景</div>
      <!-- <Popover trigger="click" placement="bottomLeft" v-model:visible="presetLayoutPopoverVisible">
        <template #content>
          <LayoutPool @select="slide => { createSlideByTemplate(slide); presetLayoutPopoverVisible = false }" />
        </template>
        <div class="select-btn"><IconDown /></div>
      </Popover> -->
    </div>
    <Draggable
      class="thumbnail-list"
      :modelValue="slides"
      :animation="200"
      :scroll="true"
      :scrollSensitivity="50"
      @end="handleDragEnd"
      itemKey="id"
    >
      <template #item="{ element, index }">
        <div
          class="thumbnail-item"
          style="flex-shrink: 0;"
          :class="{
            active: slideIndex === index,
            selected: selectedSlidesIndex.includes(index),
          }"
          :style="{ height :  scaleHight+'px'}"
          @mousedown="($event) => handleClickSlideThumbnail($event, index)"
          @click="btn(element.id)"
          v-contextmenu="contextmenusThumbnailItem"
        >
          <!-- <div class="label" :class="{ 'offset-left': index >= 99 }">
            {{ fillDigit(index + 1, 2) }}
          </div> -->
          <div class="butto">
            <div class="box-bootn">

            <IconAlarmClock
              class="iconfont"
              @click="clockfn(index)"
            ></IconAlarmClock>
            <IconDelete class="iconfont" @click="dele(index)"></IconDelete>
            <IconCopy class="iconfont" @click="copyd(index)"> </IconCopy>

          </div>

            
            <div class="po" style=" width: inherit;  position: relative;     top: 70%; right: -8%; display: flex; justify-content: space-between;   ">
        <div class="timerr">
              {{ timerzhuan(screentimer.screenyulan[index].timer) }} 
            </div>
            <div class="timerrs">{{ index +1 }}</div>
            </div>
    
          </div>
          <div
            class="gundon"
            :style="{ display: screentimer.screenyulan[index].display }"
          >
            <div>时间</div>
            <el-slider
              @change="sliderchange(index)"
              :min="3"
              :max="120"
              v-model="gundongvalue"
            />
            <div>{{ gundongvalue }}s</div>
          </div>
          <ThumbnailSlide
            class="thumbnail"
            :slide="element"
            :size="120"
            :visible="index < slidesLoadLimit"
          >
          </ThumbnailSlide>
          <div class="label"  style="position: absolute; bottom: 0px; "  :class="{ 'offset-left': index >= 99 }">
            场景000000{{ fillDigit(index + 1, 2) }}
          </div>
        </div>
      </template>
    </Draggable>

    <div class="add-slides">
      <div class="btns" @click="createSlide()">
        <img :src="require('../../../assets/adds.png')" alt="" /> 新增
      </div>
      <!-- <Popover trigger="click" placement="bottomLeft" v-model:visible="presetLayoutPopoverVisible">
        <template #content>
          <LayoutPool @select="slide => { createSlideByTemplate(slide); presetLayoutPopoverVisible = false }" />
        </template>
        <div class="select-btn"><IconDown /></div>
      </Popover> -->
    </div>
    <!-- <div class="page-number">
      场景 {{ slideIndex + 1 }} : 场景000000{{ slideIndex + 1 }}
    </div> -->
  </div>
</template>

<script lang="ts" setup>
import { computed, ref } from "vue";
import { storeToRefs } from "pinia";
import {
  useMainStore,
  useSlidesStore,
  useKeyboardStore,
  useScreenStore,
} from "@/store";
import { fillDigit } from "@/utils/common";
import { ContextmenuItem } from "@/components/Contextmenu/types";
import useSlideHandler from "@/hooks/useSlideHandler";
import useScreening from "@/hooks/useScreening";
import useLoadSlides from "@/hooks/useLoadSlides";

import ThumbnailSlide from "@/views/components/ThumbnailSlide/index.vue";
import LayoutPool from "./LayoutPool.vue";
import Draggable from "vuedraggable";
import { Popover } from "ant-design-vue";
import { Message } from "@icon-park/vue-next";
const screentimer = useScreenStore();
const mainStore = useMainStore();
const slidesStore = useSlidesStore();
import { ElMessage } from "element-plus";
const { slides, slideIndex } = storeToRefs(slidesStore);

const keyboardStore = useKeyboardStore();
const { selectedSlidesIndex: _selectedSlidesIndex, thumbnailsFocus } =
  storeToRefs(mainStore);
const { ctrlKeyState, shiftKeyState } = storeToRefs(keyboardStore);

const { slidesLoadLimit } = useLoadSlides();

const selectedSlidesIndex = computed(() => [
  ..._selectedSlidesIndex.value,
  slideIndex.value,
]);

const presetLayoutPopoverVisible = ref(false);

const {
  copySlide,
  pasteSlide,
  createSlide,
  createSlideByTemplate,
  copyAndPasteSlide,
  deleteSlide,
  cutSlide,
  selectAllSlide,
  sortSlides,
} = useSlideHandler();
function timerzhuan(a: number) {
  return `0${Math.floor(a / 60)}:${((a % 60) + "").padStart(2, "0")}`;
}

const {scaleHight} = storeToRefs( mainStore)
// 闹钟函数
function clockfn(index: number) {
  // const slide = JSON.parse(JSON.stringify(slidesStore.currentSlide))
  // navigator.clipboard.writeText(slide)
  // copyAndPasteSlide()
  // deleteSlide(index)

  gundongvalue.value = screentimer.screenyulan[index].timer;
  screentimer.setdisplay(index);

  const myProxy = new Proxy(screentimer.screenyulan, {});
  const data = myProxy[0];
  slides.value.filter((a) => {
    if (indexs.value === a[index]) {
      a.sceneTime = gundongvalue.value;
    }
  });
}
// 复制画布
function copyd() {
  copyAndPasteSlide();
}
//删除画布
function dele(index: number) {
  
  // if (index <= 0) {
  //   ElMessage({
  //     message: "当前是最后一个场景,不能删除",
  //     type: "warning",
  //   });
  // } else {
  //   deleteSlide();
  //   // screentimer.deletescreen(index);
  // }
  deleteSlide();
}

//每一条滚动条的联动值
const gundongvalue = ref(10);

// 滚动条的change事件
function sliderchange(index: number) {
  screentimer.setsend(index, gundongvalue.value);

  setTimeout(() => {
  screentimer.setdisplay(index);
  }, 2000);
}

// 切换页面
const changeSlideIndex = (index: number) => {

  mainStore.setActiveElementIdList([]);
  if (slideIndex.value === index) return;
  slidesStore.updateSlideIndex(index);
};
const indexs = ref();
const btn = (id: any) => {
  slides.value.filter((a) => {
    if (id === a.id) {
      a.Time = gundongvalue.value;
    }
  });
};
// 点击缩略图
const handleClickSlideThumbnail = (e: MouseEvent, index: number) => {
  indexs.value = index;
  const isMultiSelected = selectedSlidesIndex.value.length > 1;
  if (
    isMultiSelected &&
    selectedSlidesIndex.value.includes(index) &&
    e.button !== 0
  )
    return;

  // 按住Ctrl键，点选幻灯片，再次点击已选中的页面则取消选中
  if (ctrlKeyState.value) {
    if (slideIndex.value === index) {
      if (!isMultiSelected) return;

      const newSelectedSlidesIndex = selectedSlidesIndex.value.filter(
        (item) => item !== index
      );
      mainStore.updateSelectedSlidesIndex(newSelectedSlidesIndex);
      changeSlideIndex(selectedSlidesIndex.value[0]);
    } else {
      if (selectedSlidesIndex.value.includes(index)) {
        const newSelectedSlidesIndex = selectedSlidesIndex.value.filter(
          (item) => item !== index
        );
        mainStore.updateSelectedSlidesIndex(newSelectedSlidesIndex);
      } else {
        const newSelectedSlidesIndex = [...selectedSlidesIndex.value, index];
        mainStore.updateSelectedSlidesIndex(newSelectedSlidesIndex);
        changeSlideIndex(index);
      }
    }
  }
  // 按住Shift键，选择范围内的全部幻灯片
  else if (shiftKeyState.value) {
    if (slideIndex.value === index && !isMultiSelected) return;

    let minIndex = Math.min(...selectedSlidesIndex.value);
    let maxIndex = index;

    if (index < minIndex) {
      maxIndex = Math.max(...selectedSlidesIndex.value);
      minIndex = index;
    }

    const newSelectedSlidesIndex = [];
    for (let i = minIndex; i <= maxIndex; i++) newSelectedSlidesIndex.push(i);
    mainStore.updateSelectedSlidesIndex(newSelectedSlidesIndex);
    changeSlideIndex(index);
  }
  // 正常切换页面
  else {
    mainStore.updateSelectedSlidesIndex([]);
    changeSlideIndex(index);
  }
};

// 设置缩略图工具栏聚焦状态（只有聚焦状态下，该部分的快捷键才能生效）
const setThumbnailsFocus = (focus: boolean) => {
  if (thumbnailsFocus.value === focus) return;
  mainStore.setThumbnailsFocus(focus);

  if (!focus) mainStore.updateSelectedSlidesIndex([]);
};

// 拖拽调整顺序后进行数据的同步
const handleDragEnd = (eventData: { newIndex: number; oldIndex: number }) => {
  const { newIndex, oldIndex } = eventData;

  if (newIndex === undefined || oldIndex === undefined || newIndex === oldIndex)
    return;
  sortSlides(newIndex, oldIndex);
};

const { enterScreening, enterScreeningFromStart } = useScreening();

const contextmenusThumbnails = (): ContextmenuItem[] => {
  return [
    {
      text: "粘贴",
      subText: "Ctrl + V",
      handler: pasteSlide,
    },
    {
      text: "全选",
      subText: "Ctrl + A",
      handler: selectAllSlide,
    },
    {
      text: "新建场景",
      subText: "Enter",
      handler: createSlide,
    },
    {
      text: "节目放映",
      subText: "F5",
      handler: enterScreeningFromStart,
    },
  ];
};

const contextmenusThumbnailItem = (): ContextmenuItem[] => {
  return [
    {
      text: "剪切",
      subText: "Ctrl + X",
      handler: cutSlide,
    },
    {
      text: "复制",
      subText: "Ctrl + C",
      handler: copySlide,
    },
    {
      text: "粘贴",
      subText: "Ctrl + V",
      handler: pasteSlide,
    },
    {
      text: "全选",
      subText: "Ctrl + A",
      handler: selectAllSlide,
    },
    { divider: true },
    {
      text: "新建场景",
      subText: "Enter",
      handler: createSlide,
    },
    {
      text: "复制场景",
      subText: "Ctrl + D",
      handler: copyAndPasteSlide,
    },
    {
      text: "删除场景",
      subText: "Delete",
      handler: () => deleteSlide(),
    },
    { divider: true },
    {
      text: "从当前预览",
      subText: "Shift + F5",
      handler: enterScreening,
    },
  ];
};
</script>

<style lang="scss" scoped>
.slider-demo-block {
  display: flex;
  align-items: center;
}
.slider-demo-block .el-slider {
  margin-top: 0;
  margin-left: 12px;
}
.gundon {
  z-index: 99999991111111;
  position: absolute;
  top: 8.7rem;
  left: 1rem;
  right: -10rem;
  // top: 0;
  color: black;
  display: flex;
  justify-items: center;
  font-size: 12px;
  align-items: center;
  width: 200px;
  background-color: white;
  box-shadow: 0vh 0vh 0.6px 0.1px black;
  .el-slider {
    width: 60%;
    margin: 0 10px;

    // vertical-align: middle;
  }
  span {
    width: 30px;
    height: 30px;
    vertical-align: middle;
  }
}
.butto {
  width: inherit;
  height: inherit;
  // display: flex;
  display: none;
  position: absolute;
  top: 0.5rem;
  justify-content: space-between;
  right: 1.6rem;
  z-index: 100000;
  .box-bootn{
    position: absolute;
    right: -8%;
  }
  .iconfont {
    width: 1.5rem;
    height: 1.5rem;
    background-color: #8a94a0;
  color: white;
    text-align: center;
    line-height: 1.8rem;
    border-radius: 0.3rem;
    opacity: .7;
  }
}
.thumbnail-item:hover .butto {
  display: flex;
  // justify-content: ;
}
.timerr {
  // position: absolute;
  // bottom: 0;
  // top: 80%;
  // right: 20%;
  width: 80%;
  z-index: 100000;
  width: 4vw;
  height: 2.5vh;
  line-height: 2.5vh;
  text-align: center;
  border-radius: 0.5vh;
  background-color: #8a94a0;
  color: white;
  font-size:14px;
  opacity: .7;
}
.timerrs{
  // position: absolute;
  // bottom: 0;
  // top: 8.4rem;
  // left:  4.7rem;
  z-index: 100000;
  width: 1.2vw;
  height: 2.5vh;
  line-height: 2.5vh;
  text-align: center;
  border-radius: 0.5vh;
  background-color: #8a94a0;
  color: white;
  font-size:14px;
  opacity: .7;
}
.thumbnails {
  border-right: solid 1px $borderColor;
  background-color: #fff;
  display: flex;

  flex-direction: column;
  user-select: none;
}
.add-slide {
  height: 40px;
  font-size: 12px;
  display: flex;
  flex-shrink: 0;
  border-bottom: 1px solid $borderColor;
  cursor: pointer;

  .btn {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;

    &:hover {
      background-color: $lightGray;
    }
  }
  .select-btn {
    width: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-left: 1px solid $borderColor;

    &:hover {
      background-color: $lightGray;
    }
  }

  .icon {
    margin-right: 3px;
    font-size: 14px;
  }
}
.add-slides {
  height: 40px;
  font-size: 12px;
  margin: auto;
  display: flex;
  flex-shrink: 0;
  border-bottom: 1px solid $borderColor;
  cursor: pointer;
  width: 80%;
  margin-bottom: 50%;
  .btns {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #0daeff;
    border-radius: 5px 5px 5px 5px;

    color: #fff;
  }
  .select-btn {
    width: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-left: 1px solid $borderColor;

    &:hover {
      background-color: $lightGray;
    }
  }

  .icon {
    margin-right: 3px;
    font-size: 14px;
  }
}
.thumbnail-list {
  padding: 5px 0;
  flex: 1;
  overflow: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  align-content: center;
  
}
.thumbnail-item {
  // display: flex;
  display: inline-block;
  position: relative;
  width:95%;
  overflow: hidden;
  justify-content: center;
  align-items: center;
  // padding: 5px 0;
  margin-top: 20px;
  border: 2px solid black;
  // width: 189px;
  // height: 165px;
  // position: relative;
  // flex-wrap: wrap;
  .thumbnail {
    outline: 1px solid rgba($color: $themeColor, $alpha: 0.15);
  }

  &.active {
    .label {
      color: $themeColor;
    }
    .thumbnail {
      outline-color: $themeColor;
    }
  }
  &.selected {
    .thumbnail {
      outline-color: $themeColor;
    }
  }
}
.label {
  font-size: 12px;
  color: #999;
  margin: 8px 0;
  // width: 20px;
  cursor: grab;

  &.offset-left {
    position: relative;
    left: -4px;
  }

  &:active {
    cursor: grabbing;
  }
}
.page-number {
  height: 40px;
  font-size: 12px;
  border-top: 1px solid $borderColor;
  line-height: 40px;
  text-align: center;
  color: #666;
}
</style>
